package com.neko.Thread_Learning;

import com.neko.utils.WebDownload;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 6、实现 callable 接口
 * ----------------------
 *
 * implements Callable<T> 的好处：
 *  1、可以 自定义 返回值 + 获取 return
 *  2、可以 抛出 异常
 * */
public class t6_implements_Callable implements Callable<Boolean> {

    private String url;
    private String fileName;

    public t6_implements_Callable(String url, String name) {
        this.url = url;
        this.fileName = name;
    }

    @Override
    public Boolean call() {
        WebDownload webDownload = new WebDownload();
        webDownload.download(url, fileName);
        System.out.println("你下载了 文件名为：" + fileName);

        return true;
    }


    /**
     * Main Interface
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        t6_implements_Callable t1 = new t6_implements_Callable("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2124072373,529333338&fm=26&gp=0.jpg", "1.jpg");
        t6_implements_Callable t2 = new t6_implements_Callable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599336059576&di=59a91f0952a977ecb642092ad9356349&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201612%2F14%2F20161214221249_cCF4z.jpeg", "2.jpg");
        t6_implements_Callable t3 = new t6_implements_Callable("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2159465980,1485649590&fm=26&gp=0.jpg", "3.jpg");

        // 1、创建执行服务：执行器.新建准备好的线程池( Thread数量-》nThread ) return 执行器服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 2、执行器服务.提交( 线程 ) return 未来结果<T>
        Future<Boolean> future1 = executorService.submit(t1);
        Future<Boolean> future2 = executorService.submit(t2);
        Future<Boolean> future3 = executorService.submit(t3);

        // 3、获取结果
        Boolean aBoolean1 = future1.get();
        Boolean aBoolean2 = future2.get();
        Boolean aBoolean3 = future3.get();

        // 4、关闭服务
        executorService.shutdown();

    }

}
